<?php
namespace app\api\controller;
use app\wechat\service\JwtService;
use Decimal\Decimal;
use think\admin\Controller;
use think\Request;
use think\facade\Db;
use think\Validate;
use EasyWeChat\Factory;

use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\Darabonba\Stream\StreamUtil;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;
use think\file\UploadedFile;
/**
 * 前端管理
 */
class Code extends Controller
{
    private $person_month_limit=8;//用户月可扫数量 -积分
    private $trace_code_log = [];
    private $notify_url = 'https://myr.wissun.net';
    //码库地址
    private $maku_url = 'http://code.wissun.com';
    private $jifentable = 'scan_qrcode_log_jinfen';//积分表
    private $product_config = 'scan_product_config';//积分产品配置表
    private $scan_person_num = 0;//用户日可扫码量
    private $scan_person_total = 0;//用户日个人发放总金额数
    private $again_by_one =119;//再来一罐支付的金额
    private $jxs_integral=30;//经销商门店获取积分
    
    //明一宏业商户号
    private $myhy_options = [
        'app_id'  => 'wx504958290f5566b7',
        'secret'  => '145dc6351dde0a2ae610e8713a01e9a0',   
        'aes_key' => 'D0C1EAA33E71636574416DB12104F0EC',  
        'mch_id'  =>'1700134471',
        'key'     => 'D0C1EAA33E71636574416DB12104F0EC',
        'cert_path'=>__DIR__.'/../../cert/apiclient_cert.pem',
        'key_path'=>__DIR__.'/../../cert/apiclient_key.pem'
    ];
    private $myhy_serial_no="220485628C42716BD3583589FA43C391C70E3E8A";//序列号
    private $erpdb="erpdb";//ERP数据库
    
    //罐底码查询追溯码信息,第一次扫码
    public function code_of_trace_code(){
        ini_set ("memory_limit","-1");
        $user_id = input('user_id');
        $openid = input('openid');
        $trace_code = input('trace_code'); //追溯码   86.1000.19/06317602624421128269
        $trace_code=trim($trace_code);
        $city = input('city');//市
		$province = input('province',"");//省
		$nation = input('nation',"");//国
        $start_ta=microtime(true);//执行时间
        $validate = new Validate([
            'trace_code' => 'require|length:0,34',
            'city' => 'require',
            'openid'=>'require'
        ]);
		if(empty($city)){
            //return xcx_error('地址信息获取失败！');
        }
        $this->trace_code_log["user_id"]=$user_id;
        $this->trace_code_log["city"]=$city;
        $this->trace_code_log["trace_code"]=$trace_code;
        $this->trace_code_log["status"]=2;
		//查询用户月扫码数量
		$u_count=Db::name($this->jifentable)->where("status",1)->whereTime('create_time','month')->where("user_id",$user_id)->count();
		if($u_count >= $this->person_month_limit){
            $this->trace_code_log["status"]=2;
			return xcx_error('抱歉，您本月的参与次数已达上限，请次月再来参与~');
		}
        //增加检验用户信息
        $exuser=Db::name('wechat_userinfo')->where("id",$user_id)->find();
        if(empty($exuser)){
            $this->trace_code_log["status"]=2;
            return xcx_error('用户信息不存在');
        }
        $this->trace_code_log["user_id"]=$user_id;
        $isthree=0;//是否直接到底三页
        $card_pwd=$trace_code;
        $url = $this->maku_url . '/qrcode/aiyinghui/check_qrcode?card_pwd=' . $card_pwd;
        $card_res = json_decode(file_curl_v4($url), true);
         if (!$card_res){
            return xcx_error('罐内码查询错误');
         }
         if ($card_res['code'] == 0) {
            return xcx_error($card_res['msg']);
         }
         $card_num=$card_res["data"];
         $erpdb=Db::connect($this->erpdb);
         $localcan=$erpdb->table("localcan")->where("JFCode='".$card_num."'")->find();
         if(empty($localcan)){
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('没有找到对应的罐底码'.$card_num);
            return xcx_error('没有找到对应罐底码信息');
        }
        $trace_code=$localcan["TrackCode"];
        $isthree=1;
        $trace_code_exist = Db::name($this->jifentable)->where(['trace_code'=>$trace_code,'status'=>1])->find();
        if ($trace_code_exist){
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('罐底码已被使用');
            return xcx_error('该产品已扫过,请勿重复扫');
        }
        $user_count=Db::name($this->jifentable)->where("status",1)->where("user_id",$user_id)->count();
        $result=Db::connect($this->erpdb)->table("v_code")->where("TrackCode='".$trace_code."'")->find();
        if (!$result) {
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('SN码查询失败');
            return xcx_error('产品信息查询失败');
        }else{
            $this->trace_code_log['product_code'] = $result['ProductCD'];//料号
            $this->trace_code_log['product_name'] = $result['ProductName'];//商品名称
            $this->trace_code_log['product_batch'] = $result['BatchNO'];//商品名称
        }
        //销售范围判断逻辑
        $check_city_res = $this->check_by_to_city($trace_code, $city,$province,$nation);
        if ($check_city_res['code'] == 0) {
            $this->trace_code_log["shop_code"]=$check_city_res["data"]["shop_code"];
            $this->trace_code_log["shop_name"]=$check_city_res["data"]["shop_name"];
            $this->trace_code_log["shop_city"]=$check_city_res["data"]["shop_city"];
            $this->insert_trace_code_scan_log('用户定位与销售地不符');
            return xcx_error($check_city_res['msg']);
        }else{           
            $this->trace_code_log = array_merge($this->trace_code_log,$check_city_res['data']);
        }
        $result["shop_code"]=$check_city_res["data"]["shop_code"];
        $result["shop_name"]=$check_city_res["data"]["shop_name"];
        $result["shop_city"]=$check_city_res["data"]["shop_city"];

        $this->trace_code_log["shop_code"]=$result['shop_code'];
        $this->trace_code_log["shop_name"]=$result['shop_name'];
        $this->trace_code_log["shop_city"]=$result['shop_city'];

        //判断产品的批次，检验产品的有效日期 2年有效期
        $new_bachno=date('Ymd');//今日批次
        $result["new_bachno"]=$new_bachno;
        if(strlen($result["BatchNO"]) == 8){
            $BatchNO=$result["BatchNO"]+20000;//到期批次
        }else if(strlen($result["BatchNO"]) > 8){
            $tp="20".substr($result["BatchNO"],0,6);
            $BatchNO=$tp+20000;//到期批次
        }else{
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('罐底码批次异常'.$result["BatchNO"]);
            return xcx_error('罐底码批次异常');
        }
        
        if($new_bachno > $BatchNO){
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('罐底码码已过期');
            return xcx_error('您扫描的罐底码码已过期');
        }
        $result["exp_bachno"]=$BatchNO;
        //判断扫码产品是否增加积分
        $scan_product_config = Db::name($this->product_config)->where('product_code',$result['ProductCD'])->find();
       
        if (!$scan_product_config){
            $this->trace_code_log["status"]=2;
            $this->insert_trace_code_scan_log('该产品不参与活动');
            return xcx_error('该产品不参与活动');
        }
        //校验批次是否满足条件
        if($scan_product_config["batch"]){
            $raaar=get_product_batchno($result["BatchNO"]);
            if($raaar < $scan_product_config["batch"]){
                $this->trace_code_log["status"]=2;
                $this->insert_trace_code_scan_log('该产品不满足批次要求');
                return xcx_error('该产品不参与活动');
            }
        }
        $result["product_type"]=$scan_product_config["type"];
        $scan_log['is_newke'] = Db::name($this->jifentable)->where(['user_id'=>$user_id])->find() ? 0:1;
       
        Db::startTrans();
        //新增一条扫码记录
        $scan_log['shop_code'] = $result['shop_code'];
        $scan_log['shop_name'] = $result['shop_name'];
        $scan_log['shop_city'] = $result['shop_city'];
        $scan_log['product_code'] = $result['ProductCD'];
        $scan_log['product_name'] = $result['ProductName'];
        $scan_log['product_batch'] = $result['BatchNO'];
        $scan_log['card_num'] = $card_num;
        $scan_log['card_pwd'] = $card_pwd;
        $scan_log['openid'] = $openid;
        $scan_log['integral_num'] = $scan_product_config['integral'];
        $scan_log['num_type'] = $scan_product_config['type'];
        $scan_log['trace_code'] = $trace_code;
        $scan_log['create_time'] = date('Y-m-d H:i:s',time());
        $scan_log['update_time'] = $scan_log['create_time'];
        $scan_log['user_id'] = $user_id;
        $scan_log['city'] = $city;
        $scan_log['wd_code'] = $result["shop_code"];
        $scan_log['wd_name'] = $result["shop_name"];
        $res1 = Db::name($this->jifentable)->insertGetId($scan_log);
        if($scan_product_config['integral']){
            $res3 = Db::name('wechat_userinfo')->where('id',$user_id)->inc('integral',$scan_product_config['integral'])->update();
        }else{
            $res3=1;
        }
        
        //增加上级积分和二级经销商积分
        if($scan_product_config["parent_integral"]){
            $res6 = Db::name('jxs_lists')->where('user_code',$result["shop_code"])->inc('jxs_integral',$scan_product_config['parent_integral'])->update();
        }
        
        if($scan_product_config["secend_parent_integral"]){
            $secend_jxs_id=Db::name('jxs_lists')->where('user_code',$result["shop_code"])->value("parent_id");
            if($secend_jxs_id){
                $res7 = Db::name('jxs_lists')->where('id',$secend_jxs_id)->inc('jxs_integral',$scan_product_config['secend_parent_integral'])->update();
            }
        }
        $isdui1=$this->is6dui1($user_count);//是否直接给6兑1
        //红包抽奖方法
        $current_number = 0;
        if(!$isdui1){
            $prize=Db::name("lottery_expand_mp")
            ->where("is_delete",0)
            ->where("status",1)
            ->order('id desc')
            ->select();
            
    		$arr=[];
            foreach ($prize as $key => $val) {
                if($val["id"]==44){ continue;}
                if($val["count"]){  if($val["send_num"] >= $val["count"]){ continue; } }
    			if($val["today_limit_price"]){ 
                    $sendnum=Db::name("hongbao_date_log")->where("add_date",date("Y-m-d"))->where("lottery_id",$val["id"])->find();
                    if(empty($sendnum)){ $sendnum["send_num_count"]=0; }
    				if($sendnum["send_num_count"] >= $val["today_limit_price"]){ continue;	}
    			}
    			$arr[$val['id']] = $val['probability'];
    		}
    		if(empty($arr)){ 
                $this->insert_trace_code_scan_log('活动太火爆~,请明日再来');
                return xcx_success(['code'=>601,'msg'=>"活动太火爆~,请明日再来!！！"]); 	
            }
    		$rid = $this->get_prize($arr); //根据概率获取奖项id
    		$prize = Db::name("lottery_expand_mp")->where("id",$rid)->find();
        }else{
            $rid=44;//6兑1奖项
            $prize = Db::name("lottery_expand_mp")->where("id",$rid)->find();
            //中奖再来一罐获取30积分
            //Db::name('jxs_lists')->where('user_code',$result["shop_code"])->inc('jxs_integral',30)->update();
        }
        if(empty($prize)){ 
            $this->insert_trace_code_scan_log('活动太火爆了');
            return xcx_success(['code'=>601,'msg'=>"活动太火爆了"]); 
         }
		if($prize["today_limit_price"]){ 
            $sendnum=Db::name("hongbao_date_log")->where("add_date",date("Y-m-d"))->where("lottery_id",$prize["id"])->find();
            if($sendnum){
                if($sendnum["send_num_count"] >= $prize["today_limit_price"]){
                    $this->insert_trace_code_scan_log('活动太火爆~,请明日再来~');
                    return xcx_success(['code'=>601,'msg'=>"活动太火爆~,请明日再来~"]);
                }
            }else{
                $news=Db::name("hongbao_date_log")->insert(["add_date"=>date("Y-m-d"),"send_num_count"=>0,"lottery_id"=>$prize["id"]]);
            }
		}
        //判断个人日抽奖次数  是否大于限制
        $whm["user_id"]=$user_id;
        $whm["is_delete"]=0;
        $st=strtotime(date("Y-m-d")." 00:00:00");
        $user_num=Db::name("winrecord")->where($whm)->where("add_date",">=",$st)->count();
		if($this->scan_person_num){
			if($user_num >= $this->scan_person_num){
                $this->insert_trace_code_scan_log('已达今日上限~,请明日再来~');
                return xcx_success(['code'=>601,'msg'=>"已达今日上限~,请明日再来~"]);
			}
		}
		//判断个人当日发放金额 是否大于限制
		$user_integral=Db::name("winrecord")->where($whm)->where("add_date",">=",$st)->sum("integral");
		if($this->scan_person_total){
			if($user_integral >= $this->scan_person_total){
                $this->insert_trace_code_scan_log('已达今日上限~,请明日再来!!');
                return xcx_success(['code'=>601,'msg'=>"已达今日上限~,请明日再来!!"]);
			}
		}
        Db::name("hongbao_date_log")->where("add_date",date("Y-m-d"))->where("lottery_id",$prize["id"])
        ->inc("send_num_count",$prize["integral"])->update();//今日已发放量 增加
        Db::name("lottery_expand_mp")->where('id',$prize["id"])->inc("send_num_count",$prize["integral"])->update();//今日已发放量 增加
        Db::name("lottery_expand_mp")->where('id',$prize["id"])->inc("send_num",$prize["integral"])->update();//已发放总量  增加
        $jxskucun=Db::name("jxs_kucun")->where(["sncode"=>$trace_code,"is_send"=>0])->find();
        $wd_code="";$wd_name="";
        if($jxskucun){
            $jxs=Db::name("jxs_lists")->where("user_code",$jxskucun["jxs_code"])->find();
            $wd_code=$jxskucun["jxs_code"];
            $wd_name=$jxs["nickname"];
        }
        $user=Db::name("wechat_userinfo")->where("id",$user_id)->find();
        //增加用户中奖记录
        $windre["add_date"]=time();
        $windre["user_id"]=$user_id;
        $windre["goods_type"]=3;
        $windre["goods_name"]=$result['ProductName'];
        $windre["goods_no"]=$result['ProductCD'];
        $windre["status"]=1;
        $windre["integral"]=$prize["integral"];
        $windre["lottery_id"]=$prize["id"];
        $windre["type"]="1";
        $windre["sncode"]=$trace_code;
        $windre["incode"]=$card_num;
        $windre["city"]=$city;
        $windre["user_name"]=$user["realname"];
        $windre["mobile"]=$user["rec_mobile"];
        $windre["dis_code"]=$result['shop_code'];
        $windre["dis_name"]=$result['shop_name'];
        $windre["dis_address"]=$result['shop_city'];
        $windre['wd_code'] = $wd_code;//对应发货系统中网点编号
        $windre['wd_name'] = $wd_name;
        $windre["wx_pzh"]="N".$trace_code;//微信业务凭证号
        $res4=Db::name("winrecord")->insertGetId($windre);
    
        if($res1 && $res3 && $res4){
            //绑定第一次购买的门店编号
            if(empty($exuser["first_buy_wd"])){
                Db::name('wechat_userinfo')->where('id',$user_id)->update(["first_buy_wd"=>$wd_code]);
            }
            
            if($prize["integral"]){
                $money=$prize["integral"];
        	    $desc="扫码得红包";
        	    $openid=$user["openid"];
        	    $trade_no=$windre["wx_pzh"];
                $resultaa =$this->transfer($openid, $trade_no, $money, $desc);
                file_put_contents("hongbao.txt",date("Y-m-d")."=>".json_encode($prize).PHP_EOL,FILE_APPEND);
                file_put_contents("hongbao.txt",date("Y-m-d")."=>".json_encode($resultaa).PHP_EOL,FILE_APPEND);
                if(isset($resultaa["batch_id"])){    
                    Db::name("winrecord")->where("sncode",$trace_code)->update(["batch_id"=>$resultaa["batch_id"]]);
                    $this->trace_code_log["status"]=1;
                    $this->insert_trace_code_scan_log('查询成功');
					Db::commit();
                }else{
                    Db::rollback();
                    return xcx_error('红包发送失败');
                }
            }else{
                $this->trace_code_log["status"]=1;
                $this->insert_trace_code_scan_log('查询成功');
                Db::commit();
            }
            $json["integral"]=$scan_product_config['integral'];
            $json["prize_id"]=$prize["id"];
            $json["prize_integral"]=$prize["integral"];
            $json["sncode"]=$trace_code;
            $json["record_id"]=$res4;
            $json["product_code"]=$result['ProductCD'];
            return xcx_success($json);
        }else{
            Db::rollback();
            return xcx_error('增加积分失败');
        }
    }
    
    
     //经销商发货
    public function save_exchange_send(){
        $id=input('id');
        $record=Db::name("exchange_record")->where("id",$id)->find();
        $courier_code=input("courier_code","");
        $logistics_company=input("logistics_company","");
        if(empty($record)){
            return xcx_error('未找到订单信息~');
        }
        $result=Db::name("exchange_record")->where("id",$id)->update([
            "courier_code"=>$courier_code,
            "logistics_company"=>$logistics_company,
            "status"=>1,
            "update_time"=>date("Y-m-d H:i:s")
        ]);
        return xcx_success(['code'=>1]);
    }
    
    
     //经销商确认收货
    public function save_exchange_complate(){
        $id=input('id');
        $record=Db::name("exchange_record")->where("id",$id)->find();
        if(empty($record)){
            return xcx_error('未找到订单信息~');
        }
        $result=Db::name("exchange_record")->where("id",$id)->update([
            "complate"=>1,
            "complate_time"=>date("Y-m-d H:i:s")
        ]);
        return xcx_success(['code'=>1]);
    }
    
    
     /**post请求
     * @param $url
     * @param $param
     * @return bool|string
     */
    private function wx_post($url, $param)
    {
        
        $authorization = $this->getV3Sign_myhy($url, "POST", $param);		
        $curl = curl_init();
        $headers = [
            'Authorization:' . $authorization,
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
            'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
        curl_setopt($curl, CURLOPT_POST, true);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    /**
     * 微信提现V3签名
     * @param $url
     * @param $http_method
     * @param $body
     * @return string
     */
    private function getV3Sign_myhy($url, $http_method, $body)
    {
        $nonce = strtoupper($this->createNonceStr(32));
        $timestamp = time();
        $url_parts = parse_url($url);
        $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
        $cert_dir = "/data/project/myr.wissun.net/app/cert/apiclient_cert.pem";
        $sslKeyPath = "/data/project/myr.wissun.net/app/cert/apiclient_key.pem";
        //拼接参数
        $message = $http_method . "\n" .
            $canonical_url . "\n" .
            $timestamp . "\n" .
            $nonce . "\n" .
            $body . "\n";
        
		$private_key = openssl_get_privatekey(file_get_contents($sslKeyPath));
        openssl_sign($message, $raw_sign, $private_key, 'sha256WithRSAEncryption');
        $sign   = base64_encode($raw_sign);
        $token = sprintf('WECHATPAY2-SHA256-RSA2048 mchid="%s",nonce_str="%s",timestamp="%s",serial_no="%s",signature="%s"', $this->myhy_options["mch_id"], $nonce, $timestamp, $this->myhy_serial_no, $sign);
        
        return $token;
    }
    /**
     * 生成随机32位字符串
     * @param $length
     * @return string
     */
    public function createNonceStr($length = 16) { //生成随机16个字符的字符串
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    public function ddtest(){
      
        $money=0.3;
	    $desc="扫码得红包";
	    $openid="oMIjv643y2_P8XRIScskdDeNzICc";
	    $trade_no="N03015300716923137550";
	    $trade_no="Y".time();
        $result =$this->transfer($openid, $trade_no, $money, $desc);
        echo "<pre>";
        var_dump($result);
        echo "</pre>";
       
        
    }
    
    //商户付款到零钱-明一美优然奶粉
    private function transfer($openid, $trade_no, $money, $desc='备注说明')
    {
        $money = (int)($money * 100);
        $post_data = [
            "appid" => $this->myhy_options["app_id"],//appid
            "out_batch_no" => $trade_no,//商家批次单号
            "batch_name" => $desc,//批次名称
            "batch_remark" => $desc,//批次备注
            "total_amount" => $money,// 转账金额单位为“分”
            "total_num" => 1, // 转账总笔数
            "transfer_detail_list" => [
                [
                    'out_detail_no' => $trade_no,
                    'transfer_amount' => $money,
                    'transfer_remark' => $desc,
                    'openid' => $openid,
                ]
            ]
        ];
        $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
        $result = $this->wx_post($url, json_encode($post_data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        $result = json_decode($result, true);
        if (isset($result['prepay_id'])) {
            return $result['prepay_id'];
        }
        return $result;
    }
    
    
    
    //插入扫罐底码记录 source 1 爱婴汇积分 2新客
    private function insert_trace_code_scan_log($msg,$source=1){
        $this->trace_code_log['msg'] = $msg;
        $this->trace_code_log['create_time'] = date('Y-m-d H:i:s');
        $this->trace_code_log["source"]=$source;
        $log_id = Db::name('trace_code_scan_log')->insertGetId($this->trace_code_log);
        return $log_id;
    }
    //是否直接6对1，再来一罐
    private function is6dui1($randomNumber=0){
        $d = 6;      // 公差
        // 从第1项开始依次计算数列每一项的值，并与输入数字比较判断是否在范围内
        $n = 1;$b=false;
        while (true) {
            $currentValue =$d*$n - $d;
            if ($currentValue == $randomNumber) {
                //echo "该数字在数列的值范围内，它是第". $n. "项的值\n";
                $b=true;
                break;
            } elseif ($currentValue > $randomNumber) {
                //echo "该数字不在数列的值范围内\n";
                //return false;
                break;
            }
            $n++;
        }
        return $b;
    }
    
    
    //抽奖概率计算
	private function get_prize($proArr) {
		$result = '';
		$proSum = array_sum($proArr);
		foreach ($proArr as $key => $proCur) {
			$randNum = mt_rand(1, $proSum);
			if ($randNum <= $proCur) {
				$result = $key;
				break;
			} else {
				$proSum -= $proCur;
			}
		}
		unset ($proArr);
		return $result;
	}
    
    //检查城市是否符合扫码条件 走的是我们自己阿里云数据
    public function check_by_to_city($sn_code, $city,$province="",$nation="")
    {
         $kucun=Db::name("jxs_kucun")->where(["sncode"=>$sn_code,"is_send"=>0])->order("id desc")->find();
         if(empty($kucun)){
             return ['code' => 0, 'msg' => '产品销售地与用户定位不符!!'];
         }
         $jxs_code=Db::name("jxs_lists")->where(["user_code"=>$kucun["jxs_code"] ])->find();
         if($jxs_code["role"] != 4){
              return ['code' => 0, 'msg' => '产品未在门店中!'];
         }
         $areas=Db::name("jxs_areas")->where("jxs_code",$jxs_code["user_code"])->select();
         $check=false;$district=[];
         foreach ($areas as $kk=>$val){
             $u=Db::name("cnarea_2023")->where("area_code",$val["district"])->value("name");
             array_push($district,$u);
             if($u == $city){ $check=true;  break; }
         }
         if($check){
             return [
                'code' => 1,
                'data'=>[
                    'shop_code'=>$jxs_code["user_code"],
                    'shop_name'=>$jxs_code["nickname"],
                    'shop_city'=>implode(",",$district)
                ]
             ];
         }else{
             return [
                'code' => 0, 
                'msg' => '产品销售地与用户定位不符!',
                'data'=>[
                    'shop_code'=>$jxs_code["user_code"],
                    'shop_name'=>$jxs_code["nickname"],
                    'shop_city'=>implode(",",$district)
                ]
            ];
         }
    }
    
    //再来一罐获取产品信息
    public function duihuanbyone(){
        
        $record_id = input('id');
        $trace_code = input('trace_code');
        $trace_code=trim($trace_code);
        $winrecord=Db::name("winrecord")->where("id",$record_id)->find();
        if(empty($winrecord)){
            return xcx_error('未查到中奖信息~');
        }
        $winrecord2=Db::name("again_record")->where("sn_code",$trace_code)->find();
        if($winrecord2){
            if($winrecord2["order_status"] == 1){
                return xcx_error('产品已兑换,请勿重复兑换~');
            }
        }
        
        //再来一罐
        if($winrecord["lottery_id"] == 44){
            $datalist["goods_info"]=["name"=>$winrecord["goods_name"],"amount"=>$this->again_by_one];
            return xcx_success($datalist);
        }
        
    }
    
     //创建微信支付订单并返回json-抽奖再来一罐
     public function get_order_json_beibi_myhy_again()
     {
         $request_data = input('post.');
         $validate = new Validate([
             'user_id' => 'require|number',
             'trace_code' => 'require|number',
             'address_id'=>'require|number',
             'open_id'=>'require',
             'product_code'=>'require'
         ]);
         $check_res = $validate->check($request_data);
         if (!$check_res) {
             return xcx_success(['code'=>2,'msg'=>$validate->getError()]);
         }
         $traceinfo=Db::name("again_record")->where(["sn_code"=>$request_data["trace_code"]])->find();
         if($traceinfo){
              if($traceinfo["order_status"] == 1){
                  return xcx_success(['code'=>2,'msg'=>'您已兑换，请勿重复兑换']);
              }else if($traceinfo["order_status"] == 0){
                  Db::name("again_record")->where(["id"=>$traceinfo["id"]])->delete();
              }
         }
         $user_info = Db::name('wechat_userinfo')->where(['id' => $request_data['user_id']])->find();
         if (!$user_info) {
             return xcx_success(['code'=>2,'msg'=>'未找到用户']);
         }
         $erpdb=Db::connect($this->erpdb);
         $vcode=$erpdb->table("v_code")->where("TrackCode='".$request_data["trace_code"]."'")->find();
         $address_info = Db::name('user_address')->where(['id'=>$request_data['address_id'],'status'=>1])->find();
        if (!$address_info){
             return xcx_error('地址错误！');
        }
        $user_scan=Db::name("scan_qrcode_log_jinfen")->where(["status"=>1,"trace_code"=>$request_data["trace_code"]])->find();
        if(empty($user_scan)){
            return xcx_error('无扫码记录！');
        }
        $user_scan=Db::name("scan_qrcode_log_jinfen")->where(["status"=>1,"user_id"=>$request_data["user_id"]])->order("id asc")->find();
        if($user_info["first_buy_wd"]){
            $user_scan["wd_code"]=$user_info["first_buy_wd"];
            $user_scan["wd_name"]=Db::name("jxs_lists")->where("user_code",$user_info["first_buy_wd"])->value("nickname");
        }


        try {
             $goods_info['amount']=$this->again_by_one;//支付金额
             $out_trade_no = "my" . date("YmdHis") . "ZT" . rand(0, 10000);
             //创建兑换记录
             $exchange_log['add_time'] = date("Y-m-d H:i:s");
             $exchange_log["sn_code"]=$request_data["trace_code"];
             $exchange_log['goods_name'] = $vcode['ProductName'];
             $exchange_log['user_id'] = $request_data['user_id'];
             $exchange_log['status'] = 0;
             $exchange_log['is_delete'] = 0;
             $exchange_log['dis_code'] = $user_scan['wd_code'];
             $exchange_log['dis_name'] = $user_scan['wd_name'];
             $exchange_log['order_no'] = $out_trade_no;
             $exchange_log['wx_mchid_order_no'] = $out_trade_no;
             $exchange_log['goods_no'] = $vcode['ProductCD'];  //商品表id
             $exchange_log['pay_price'] = $goods_info['amount'];
             $exchange_log['jushuitan_send'] =1;//抛送聚水潭  1抛送 0不抛送
             $exchange_log['nickname'] = $user_info['nickname'];
             $exchange_log['username'] = $address_info['rec_user_name']; //姓名
             $exchange_log['mobile'] = $address_info['rec_mobile'];
             $exchange_log['address'] = $address_info['ad1'].$address_info['ad2'].$address_info['ad3'].$address_info['detail'];
             $exchange_log['address_id'] = $request_data['address_id'];
             $exchange_log['order_status'] = 0;    //需要付款则状态改为未付款，无需付款则改为已付款
             $inser_exchange_log_res = Db::name('again_record')->insertGetId($exchange_log);
             
             //判断是否需要支付现金
             if ($goods_info['amount'] > 0) {
                 //需要支付现金则调微信支付接口
                 $open_id = $request_data["open_id"];
                 $app = Factory::payment($this->myhy_options);
                 $attributes = [
                     'trade_type' => 'JSAPI', 
                     'body' => '再来一罐兑换',
                     'detail' => $vcode['ProductName'],
                     'out_trade_no' => $out_trade_no,
                     'total_fee' => $goods_info['amount'] * 100, // 单位：分
                     'notify_url' => $this->notify_url . '/api/code/wechat_pay_notify_beibi_myhy2', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                     'openid' => $open_id,
                     'attach' => ''
                 ];
                 $result = $app->order->unify($attributes);
                 if ($result["return_code"] == 'SUCCESS' && $result["result_code"] == 'SUCCESS') {
                    $jssdk = $app->jssdk;
                    $prepayId = $result["prepay_id"];
                    $json = $jssdk->bridgeConfig($prepayId, false); // 返回数组
                    if ($json && $inser_exchange_log_res) {
                         Db::name('again_record')->where(['id'=>$inser_exchange_log_res])->update(['pay_json'=>json_encode($json)]);
                         Db::commit();
                         return xcx_success(['code' => 1, 'msg' => 'create json success', 'data' => $json]);
                     } else {
                         Db::rollback();
                         return xcx_success(['code' => 2, 'msg' => '支付订单创建失败~~']);
                     }
                 } else {
                     Db::rollback();
                     return xcx_success(['code' => 2, 'msg' => $result->err_code_des]);
                 }
             }else{
                 Db::name('again_record')->where("id",$inser_exchange_log_res)->update(["order_status"=>1,"update_time"=>date('Y-m-d H:i:s')]);
                 if($user_info["first_buy_wd"]){
                    Db::name('jxs_lists')->where('user_code',$user_info["first_buy_wd"])->inc('jxs_integral',$this->jxs_integral)->update();
                 }else{
                    Db::name('jxs_lists')->where('user_code',$exchange_log["dis_code"])->inc('jxs_integral',$this->jxs_integral)->update();
                 }
                 return xcx_success(['code' => 0, 'msg' => 'create json success']);
             }
         } catch (Exception $exception) {
             return xcx_success($exception->getMessage());
         }
     }
    
    
    //再来一罐-拉起微信支付
	public function get_wxpay_json3(){
		$request_data = input('post.');
        $validate = new Validate([
            'user_id' => 'require|number',
			'log_id' => 'require|number',
            'openid'=>'require'
        ]);
		$check_res = $validate->check($request_data);
        if (!$check_res) {
            return xcx_success(['code'=>2,'msg'=>$validate->getError()]);
        }
		$user_info = Db::name('wechat_userinfo')->where(['id' => $request_data['user_id']])->find();
        if (!$user_info) {
            return xcx_success(['code'=>2,'msg'=>'未找到用户']);
        }
		$record_data=Db::name("again_record")->where("id",$request_data["log_id"])->find();
		if($record_data){
            $app = Factory::payment($this->myhy_options);
			$out_trade_no = "my" . date("YmdHis") . "ZT" . rand(0, 10000);
            $attributes = [
                'trade_type' => 'JSAPI',
                'body' => '再来一罐兑换',
                'detail' => $record_data['goods_name'],
                'out_trade_no' => $out_trade_no,
                'total_fee' => $record_data['pay_price'] * 100,
                'notify_url' => $this->notify_url . '/api/code/wechat_pay_notify_beibi_myhy2', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid' => $request_data["openid"],
                'attach' => ''
            ];
			$result = $app->order->unify($attributes);
            if ($result["return_code"] == 'SUCCESS' && $result["result_code"] == 'SUCCESS') {
                $jssdk = $app->jssdk;
                $prepayId = $result["prepay_id"];
                $json = $jssdk->bridgeConfig($prepayId, false); // 返回数组
                $result["out_trade_no"]=$out_trade_no;
                Db::name('again_record')->where(['id'=>$record_data["id"]])->update(['pay_json'=>json_encode($json),"order_no"=>$out_trade_no]);
                return xcx_success(['code'=>1,'msg'=>"success","data"=>$json]);
            }else{
                return xcx_success(['code'=>2,'msg'=>$result->err_code_des]);
            }
        }
	}
    //再来一罐兑换支付回调 
    public function wechat_pay_notify_beibi_myhy2()
    {
        $app = Factory::payment($this->myhy_options);
        $response = $app->handlePaidNotify(function($notify, $successful){
            $order = Db::name('again_record')->where(['order_no' => $notify['out_trade_no']])->find();
            if (!$order) {  return 'Order not exist.';   }
            if ($order['order_status'] == 1) {  return true;  }
            if ($successful) {
                // 不是已经支付状态则修改为已经支付状态
                $rrea=Db::name('again_record')->where(['order_no' => $notify['out_trade_no'], 'order_status' => 0])->update([
                    'order_status' => 1, 
                    'update_time' => date('Y-m-d H:i:s'),
                    'pay_time'=>time(),
                    'notify'=>json_encode($notify)
                ]);
                if($rrea){
                    Db::name('jxs_lists')->where('user_code',$order["dis_code"])->inc('jxs_integral',30)->update();
                }
            }
            return true; 
        });
        return $response;
    }
    
    //上传图片，返回url
    public function xklb_upload()
    {
        $domain_url = 'https://myr.wissun.net';
        $path = './upload/yyzz/' . date('Y-m-d') . '/';
        $file = $this->request->file('image');
        $token = $this->request->header('token');
        if (!is_dir($path)) {
            mkdir($path);
        }
        $new_file_name = time().".png";
        $info = $file->move($path, $new_file_name);
        if ($info) {
            $new_file_path = $domain_url . trim($path, '.') . $new_file_name;
            return xcx_success(['url' => $new_file_path]);
        } else {
            return xcx_error($file->getError());
        }
    }
    
    //保存网点信息（网点招募）
    public function save_wd_info(){
        $param = $this->request->param();
        $validate = new Validate([
            'ying_ye_zhi_zao' => 'require',
            'netname' => 'require',
            'bossphone' => 'require',
            'netaddr' => 'require',
            'jxs_code' => 'require',
            'nickname' => 'require',
            'yyzz_pic' => 'require',
            'longitude' => 'require',
            'latitude' => 'require',
            'district' => 'require',
            'province' => 'require',
            'city' => 'require',
            'detail' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 1, 'message' => $validate->getError()]);
        }
        file_put_contents("wd_info.txt",date("Y-m-d H:i:s")."=>".json_encode($param,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
        $whe["ying_ye_zhi_zao"]=$param["ying_ye_zhi_zao"];
        $isexit=Db::name("jxs_lists")->where($whe)->find();
        if($isexit){
            return json(['code' => 1, 'message' =>"营业执照编号已存在！"]);
        }
        $jxscode=Db::name("jxs_lists")->where("user_code",$param["jxs_code"])->find();
        $jxsarea=Db::name("jxs_areas")->where(["jxs_code"=>$param["jxs_code"]])->find();
        if(empty($jxsarea)){
            return json(['code' => 1, 'message' =>"请设置经销商销售区域！"]);
        }
        $prinvin_code=Db::name("cnarea_2023")->where("name",$param["province"])->value("area_code");
        
        $city_code=Db::name("cnarea_2023")->where("name",$param["city"])->where("parent_code",$prinvin_code)->value("area_code");
        if(empty($city_code)){
            $city_code=Db::name("cnarea_2023")->where("name","省直辖县级行政区划")->where("parent_code",$prinvin_code)->value("area_code");
            if(empty($city_code)){
                $city_code=Db::name("cnarea_2023")->where("name","市辖区")->where("parent_code",$prinvin_code)->value("area_code");
            }
        }
        $district=Db::name("cnarea_2023")->where("name",$param["district"])->where("parent_code",$city_code)->value("area_code");
        if(empty($district)){
            //找不到区县位置
            $jxsarea=Db::name("jxs_areas")->where(["jxs_code"=>$param["jxs_code"],"city"=>$city_code])->find();
            
        }else{
            $jxsarea=Db::name("jxs_areas")->where(["jxs_code"=>$param["jxs_code"],"district"=>$district])->find();
        }
        
        if(empty($jxsarea)){
            return json(['code' => 1, 'message' =>"该门店不属于经销商区域！"]);
        }
        
        $curr_user_code=Db::name("jxs_lists")->where("user_code","like","%".date("Ymd")."%")->order("user_code desc")->value("user_code");
        if($curr_user_code){
            $user_code=$curr_user_code+1;
        }else{
            $user_code=date("Ymd")."001";
        }
        $insert["user_code"]=$user_code;
        $insert["username"]=$param["bossphone"];
        $insert["nickname"]=($param["netname"] == "暂无")?$param["netname2"]:$param["netname"];
        $insert["password"]="123456";
        $insert["role"]=4;
        $insert["add_time"]=date("Y-m-d H:i:s");
        $insert["uniacid"]=1;
        $insert["parent_id"]=$jxscode["id"];
        $insert["ying_ye_zhi_zao"]=$param["ying_ye_zhi_zao"];
        $insert["yyzz_pic"]=$param["yyzz_pic"];
        
        $insert["latitude"]=$param["latitude"];
        $insert["longitude"]=$param["longitude"];
        $insert["city"]=$city_code;
        $insert["province"]=$prinvin_code;
        $insert["district"]=$district;
        $insert["detail"]=$param["province"]." ".$param["city"]." ".$param["district"]." ".$param["detail"];
        
        $newid=Db::name("jxs_lists")->insert($insert);
        if($newid){
            $area["jxs_code"]=$user_code;
            $area["province"]=$insert["province"];
            $area["city"]=$insert["city"];
            $area["district"]=$insert["district"];
            Db::name("jxs_areas")->insert($area);
        }
        return json(['code' => 200, 'message' =>"提交成功！"]);
       
    }
    
    //识别营业执照的内容
    public function shibie_yyzz(){
        ini_set('memory_limit', '256M');
        $pic=input("pic","");
        if(empty($pic)){
            return json(['code' => 0,"message"=>"参数不能为空"]);
        }
        $accessKeyId = 'LTAI5t6HbthecH3XZWZfaWY1';
        $accessKeySecret = 'ZM7YMKpDiXnO6S3F69UgtPsNepNPyu';
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        $client = new OpenApiClient($config);
        $params = new Params([
            "action" => "RecognizeBusinessLicense",
            "version" => "2021-07-07",
            "protocol" => "HTTPS",
            "method" => "POST",
            "authType" => "AK",
            "style" => "V3",
            "pathname" => "/",
            "reqBodyType" => "json",
            "bodyType" => "json"
        ]);
        $pic=str_replace("https://myr.wissun.net/","",$pic);
        //$pic="/public/".$pic;
        $bodyStream = StreamUtil::readFromFilePath($pic);
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "stream" => $bodyStream
        ]);
        $result = $client->callApi($params, $request, $runtime);
        trace("识别结果",json_encode($result,JSON_UNESCAPED_UNICODE));
        return json(['code' => 200, 'data' => $result]);
    }
    
     //根据经纬度获取定位城市
    public function get_city()
    {
        $latitude = input('latitude');
        $longitude = input('longitude');
        $validate = new Validate([
            'latitude' => 'require|float',
            'longitude' => 'require|float'
        ]);
        $check_res = $validate->check(['latitude' => $latitude, 'longitude' => $longitude]);
        if (!$check_res) {
            return xcx_error($validate->getError());
        } else {
            $url = 'http://v.wissun.net/activity/check_user_address/?latitude=' . $latitude . '&longitude=' . $longitude;
            $res = file_curl_v4($url);
            $result=json_decode($res, true);
            $district=$result["result"]["ad_info"]["district"];
            if(empty($district)){
                $district=$result["result"]["ad_info"]["city"];
                $result["result"]["ad_info"]["district"]=$district;
            }

            if($district == "太和县"){
                //取第二个地址选项
                if(isset($result["result"]["pois"][1])){
                    $pois=$result["result"]["pois"][1]["ad_info"]["district"];
                    $district=$district.','.$pois;
                }
            }

            $result["result"]["address_component"]["district"]=$district;
            return xcx_success($result);
        }
    }
    
}